import { memo, useEffect, useState } from "react";
import { useAppDispatch, useAppSelector } from "../../../store";
import {
  fetchDeleteArticleAction,
  fetchGetArticleListAction,
} from "../../../store/modules/article";
import { ArticleWrapper } from "./style";
import SearchItems, {
  type ISearchFormItem,
} from "../../../commponts/SearchItems";
import { Button, Image, Message, Modal, Table } from "@arco-design/web-react";
import {
  IconPlus,
  IconEdit,
  IconDownload,
  IconDelete,
} from "@arco-design/web-react/icon";
import dayjs from "dayjs";
import { mapState } from "../../../utils/mapState";
import { fetchDeleteLeaveWordAction } from "../../../store/modules/leaveWord";
import ModifyArticle from "./Modify";
const ArticePage = () => {
  const dispatch = useAppDispatch();
  //?表单页面state
  const [pageSize, setPageSzie] = useState(10);
  const [pageNum, setPageNum] = useState(1);
  //?选择框state
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
  //?redux获取数据
  const { articleList, total } = useAppSelector((state) => state.article);
  //*是否删除state
  const [isDelete, setIsDelete] = useState(false);
  //*修改新增模块对话框state
  const [visible, setVisible] = useState(false);
  const [mode, setMode] = useState<"add" | "edit">("edit");
  const [currentId, setCurrentId] = useState<number | null>(null);
  //*过滤state
  const [searchParams, setSearchParams] = useState<{
    articleTitle: string | null;
    articleState: string;
  }>({
    articleTitle: "",
    articleState: "",
  });
  //*这样写可以父传子更新表单数据，表单数据重新渲染
  const fetchArticleList = async () => {
    await dispatch(fetchGetArticleListAction({ pageNum, pageSize }));
  };
  useEffect(() => {
    fetchArticleList();
  }, [dispatch, pageNum, pageSize]);

  //*父传子相关函数start
  const handleModify = () => {
    if (selectedRowKeys.length < 1) {
      Message.warning("请选择一行进行修改");
      return;
    }
    setMode("edit");
    setCurrentId(Number(selectedRowKeys[selectedRowKeys.length - 1]));
    setVisible(true);
  };
  const handleAdd = () => {
    setMode("add");
    setCurrentId(null); // 新增没有 id
    setVisible(true);
  };
  const handleSelectedClose = () => {
    setSelectedRowKeys([]);
  };
  //*end

  //*过滤模块数据
  const searchItems: ISearchFormItem[] = [
    {
      type: "input",
      field: "articleTitle",
      label: "文章标题",
      placeholder: "请输入文章标题",
    },
    {
      type: "select",
      field: "state",
      label: "文章状态",
      placeholder: "请选择文章状态",
      options: [
        {
          label: "未发布",
          value: 0,
        },
        {
          label: "已发布",
          value: 1,
        },
      ],
    },
  ];
  const handleSearch = (values: any) => {
    setSearchParams({
      articleTitle: values?.articleTitle,
      articleState: values?.state,
    });
  };

  //*选择框逻辑
  const onSelectChange = (newSelectedRowKeys: any[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
    // console.log(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  //*删除
  const deleteArticle = async () => {
    await dispatch(fetchDeleteArticleAction(selectedRowKeys));
    setIsDelete(false);
    setSelectedRowKeys([]);
  };
  const columns = [
    { title: "文章id", dataIndex: "id" },
    { title: "文章标题", dataIndex: "articleTitle" },
    {
      title: "首页图片",
      dataIndex: "articlePic",
      render: (value: string) => {
        return <Image src={value} width={80} height={50} />;
      },
    },
    { title: "点赞数", dataIndex: "likeNum" },
    {
      title: "发布状态",
      dataIndex: "state",
      render: (value: string) => {
        if (value === "0") return <span>未发布</span>;
        else return <span>已发布</span>;
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      render: (value: string) => {
        return <span>{dayjs(value).format("YYYY年MM月DD日")}</span>;
      },
    },
    {
      title: "操作",
      dataIndex: "movement",
      render: (value: any, record: any) => {
        return (
          <div>
            <Button
              type="text"
              status="success"
              icon={<IconEdit />}
              onClick={() => {
                setSelectedRowKeys([record.id]);
                setMode("edit");
                setCurrentId(record.id);
                setVisible(true);
              }}
            >
              修改
            </Button>
            <Button
              onClick={() => {
                // if (selectedRowKeys.length < 1) {
                //   Message.warning("请选择修改行");
                //   return;
                // }
                setSelectedRowKeys([record.id]);
                setIsDelete(true);
              }}
              type="text"
              status="danger"
              icon={<IconDelete />}
            >
              删除
            </Button>
          </div>
        );
      },
    },
  ];
  const data = articleList?.map((item) => {
    return {
      id: item.id,
      articleTitle: item.title,
      articlePic: `http://119.29.235.74:20242${item.image}`,
      likeNum: item.likes,
      state: item.state,
      createTime: item.createTime,
    };
  });
  const filterData = data?.filter((item) => {
    const matchTitle =
      !searchParams.articleTitle ||
      item?.articleTitle?.includes(searchParams.articleTitle);
    const matchState =
      !searchParams.articleState ||
      item.state === String(mapState(searchParams.articleState));
    return matchTitle && matchState;
  });

  return (
    <ArticleWrapper>
      <Modal
        title="警告"
        onCancel={() => {
          setIsDelete(false);
          setSelectedRowKeys([]);
        }}
        onOk={deleteArticle}
        visible={isDelete}
      >
        <p style={{ textAlign: "center" }}>
          你确定要删除id为{selectedRowKeys.join(",")}的文章吗？
        </p>
      </Modal>
      <ModifyArticle
        visible={visible}
        mode={mode}
        id={currentId}
        onClose={() => setVisible(false)}
        onCloseSelected={handleSelectedClose}
        onRefresh={fetchArticleList}
      />
      <SearchItems items={searchItems} onSearch={handleSearch} />

      <div className="centerWrapper">
        <Button
          icon={<IconPlus />}
          type="primary"
          onClick={handleAdd}
          className="btn"
        >
          新增
        </Button>
        <Button
          icon={<IconEdit />}
          type="primary"
          status="success"
          className="btn"
          onClick={handleModify}
          disabled={selectedRowKeys.length < 1}
        >
          修改
        </Button>
        <Button
          disabled={selectedRowKeys.length < 1}
          onClick={() => {
            setIsDelete(true);
          }}
          className="btn"
          icon={<IconDelete />}
          type="primary"
          status="danger"
        >
          删除
        </Button>
        <Button
          className="btn"
          icon={<IconDownload />}
          type="primary"
          status="warning"
          onClick={() => {
            Modal.warning({
              title: "通知",
              content: "导出接口崩了，正在维修中。。。",
              okText: "关闭",
            });
          }}
        >
          导出
        </Button>
      </div>

      <div className="table">
        <Table
          rowSelection={rowSelection}
          rowKey={(record) => record.id}
          columns={columns}
          data={filterData}
          style={{ userSelect: "none" }}
          pagination={{
            total: total,
            sizeOptions: [10, 20, 30],
            showJumper: true,
            pageSize: pageSize,
            current: pageNum,
            showTotal: (total) => `共${total}条`,
            sizeCanChange: true,
            onChange: (current, pageSize) => {
              // console.log(current, pageSize);
              setPageNum(current);
              setPageSzie(pageSize);
            },
            style: {
              marginRight: "15px",
            },
          }}
        />
      </div>
    </ArticleWrapper>
  );
};
export default memo(ArticePage);
